package com.linkoog.devtools.websocket.toolwindow;

import com.intellij.icons.AllIcons;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ex.ToolWindowEx;
import com.intellij.ui.components.OnOffButton;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.ui.content.ContentManagerListener;
import com.intellij.ui.content.impl.ContentImpl;
import com.intellij.util.ModalityUiUtil;
import com.intellij.util.keyFMap.KeyFMap;
import com.intellij.util.ui.JBUI;
import com.linkoog.devtools.utils.CricleNumber;
import kotlin.Unit;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;

public class WebscoketToolWindowManager implements Disposable {

    String TOOL_WINDOW_ID = "com.linkoog.devtools.Websocket";
    String TOOL_WINDOW_NAME = "Websocket";
    private final Project project;

    private final static CricleNumber cricleNumber = new CricleNumber(12, false);
    private final static Icon socket_icon = IconLoader.getIcon("/icons/websocket/socket.svg", WebscoketToolWindowManager.class);

    public WebscoketToolWindowManager(@NotNull Project project) {
        this.project = project;
    }


    public static WebscoketToolWindowManager getInstance(@NotNull Project project){
        return project.getService(WebscoketToolWindowManager.class);
    }


    @Override
    public void dispose() {
    }

    public @NotNull ToolWindowEx getOrCreateToolWindow() {
        ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
        ToolWindowEx toolWindowEx = (ToolWindowEx)toolWindowManager.getToolWindow(TOOL_WINDOW_ID);
        if (toolWindowEx != null) {
            if (toolWindowEx.getContentManager().isEmpty()){
                ToolWindowEx finalToolWindowEx = toolWindowEx;
                SwingUtilities.invokeLater(() -> addContent(finalToolWindowEx));
            }
            return toolWindowEx;
        }


        toolWindowEx = (ToolWindowEx)toolWindowManager.registerToolWindow(TOOL_WINDOW_ID, builder -> {
            builder.stripeTitle = () -> TOOL_WINDOW_NAME;
            builder.icon = socket_icon;
            builder.canCloseContent = true;
            builder.hideOnEmptyContent = true;
            builder.anchor = ToolWindowAnchor.BOTTOM;
            builder.sideTool = false;  //是否右边,有其他激活的面板，则合并显示在其他toolwindow右边
            return Unit.INSTANCE;
        });
        toolWindowEx.setAutoHide(true);


        ToolWindowEx finalToolWindowEx = toolWindowEx;
        addContent(finalToolWindowEx);
        AnAction addDailogAction = new AnAction("add", "add", AllIcons.General.Add){
            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
                Project project = e.getProject();
                if (project == null) return;

                addContent(finalToolWindowEx);
            }

            @Override
            public void update(@NotNull AnActionEvent e) {
                final int count = finalToolWindowEx.getContentManager().getContentCount();
                e.getPresentation().setEnabledAndVisible(count <= 5);
            }

            @Override
            public boolean isDumbAware() {
                return true;
            }

            @Override
            public @NotNull ActionUpdateThread getActionUpdateThread() {
                return ActionUpdateThread.EDT;
            }
        };
        finalToolWindowEx.setTabActions(addDailogAction);
        return toolWindowEx;
    }

    public void show(){
        invokeLaterIfNeeded(() -> {
            getOrCreateToolWindow().show();
        });
    }

    private void addContent(ToolWindowEx toolWindowEx){
        WebsocketContentPanel jPanel = new WebsocketContentPanel(project);

        ContentManager contentManager = toolWindowEx.getContentManager();
        final int count = contentManager.getContentCount();
        ContentImpl content = new ContentImpl(jPanel.getMyMainPanel(), "tab" + (count+1), false);
        //content.setCloseable(false);
        contentManager.addContent(content);
        contentManager.setSelectedContent(content);
        Disposer.register(content, jPanel);
    }


    public void addContent() {
        invokeLaterIfNeeded(() -> {
            addContent(getOrCreateToolWindow());
        });
    }

    public void removeContent(Content content) {
        invokeLaterIfNeeded(() -> {
            ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(TOOL_WINDOW_ID);
            ContentManager contentManager = toolWindow == null ? null : toolWindow.getContentManager();
            if (contentManager != null && !contentManager.isDisposed()) {
                contentManager.removeContent(content, true);
            }
        });
    }

    private void invokeLaterIfNeeded(@NotNull Runnable runnable) {
        if (project.isDefault()) {
            return;
        }

        StartupManagerEx.getInstanceEx(project).runAfterOpened(() -> {
            ModalityUiUtil.invokeLaterIfNeeded(ModalityState.defaultModalityState(), project.getDisposed(), runnable);
        });
    }






}
